package br.com.iswe.gwt.ui.client.comp;

import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class MaskTextField extends TextBox {

	private String mask;
	
	private boolean caractereMask = false;

	public MaskTextField(String label, String textMask) {
		super();
		this.mask = textMask;
		super.addKeyboardListener(new KeyboardListener() {
			public void onKeyDown(Widget sender, char keyCode, int modifiers) {
			}
			public void onKeyPress(Widget sender, char keyCode, int modifiers) {
				String text = ((TextBox) sender).getText();
				int length = length();
				
				if (length >= mask.length() && keyCode!=KEY_BACKSPACE) {
					((TextBox) sender).cancelKey();
					return;
				} else if(keyCode!=KEY_BACKSPACE){
					int nextIndex = mask.indexOf('#', length);
					String currentMask = "";
					if (nextIndex >= 0){
						if(length==nextIndex){
							currentMask = mask.substring(length, nextIndex+1);
						} else {
							currentMask = mask.substring(length, nextIndex);
						}
					}else{
						currentMask = mask.substring(length);
					}
					
					if (!currentMask.equals("#")){
						((TextBox) sender).setText(text + currentMask);
					}
				}			
			}
			public void onKeyUp(Widget sender, char keyCode, int modifiers) {
			}
		});
	}

	public String getText() {
		String origtext = super.getText();
		String strip = "";
		try {
			for (int i = 0; i < origtext.length(); i++) {
				if (Character.isDigit(origtext.charAt(i)))
					strip = strip.concat(String.valueOf(origtext.charAt(i)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strip;
	}
	
	public int length(){
		return super.getText().length();
	}

	public void setText(String text) {
		String fmt = "";
		int textcnt = 0;
		if (text == null || length() == 0) {
			super.setText(text);
			return;
		}

		try {
			for (int i = 0; i < mask.length() && i <= length(); i++) {
				//verifica se na mascara tem o caracter # e se o text eh menor do que o indice e concatena o valor do text
				if (mask.charAt(i) == '#' && !(length()==textcnt)) {
					fmt = fmt.concat(text.substring(textcnt, textcnt + 1));
					textcnt++;
					//verifca se eh diferente do caracter # e inclui a mascara no campo
				} else if(!(mask.charAt(i) == '#')){
					fmt = fmt.concat(mask.substring(i, i + 1));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.setText(fmt);
	}
}
